<?php
/**
 * Created by PhpStorm.
 * User: 64423
 * Date: 2018/10/9
 * Time: 17:37
 */

namespace app\shop\admin;

use app\admin\controller\Admin;
use app\common\builder\ZBuilder;
use app\shop\model\GoodsCategoryModel;

class GoodsCategory extends Admin
{
    public function index()
    {
        $list = GoodsCategoryModel::getList();
        $newList = categoryTree($list);

        $rows = [
            ['id','ID'],
            ['name','分类名称'],
            ['pid','上级ID'],
            ['img','缩略图','picture'],
            ['right_button','操作']
        ];
        return ZBuilder::make('table')
            ->setPageTitle('分类列表')
            ->setTableName('goods_category')
            ->addColumns($rows)
            ->addTopButton('add')
            ->addRightButtons('edit,delete')
            ->setRowList($newList)
            ->fetch();
    }

    public function add()
    {
        if(request()->isPost()){
            $data = input('post.');
            $this->store($data);
        }
        $arr = $this->getTopList();
        return ZBuilder::make('form')
            ->setPageTitle('添加分类')
            ->setUrl(url('add'))
            ->isAjax(false)
            ->addFormItem('text','name','分类名称')
            ->addSelect('pid','上级分类','',$arr,'0')
            ->addImage('img','图片','规格80*80 小于100kb','0')
            ->addFormItem('text','sort','排序','','0')
            ->fetch();
    }

    public function edit($id = 0)
    {
        if(request()->isPost()){
            $data = input('post.');
            $this->store($data, $id);
        }
        $arr = $this->getTopList();
        $data = GoodsCategoryModel::getOne($id);
        return ZBuilder::make('form')
            ->setPageTitle('编辑分类')
            ->setUrl(url('edit'))
            ->isAjax(false)
            ->addHidden('id',$id)
            ->addFormItem('text','name','分类名称')
            ->addSelect('pid','上级分类','',$arr,'0')
            ->addImage('img','图片','规格80*80 小于100kb','0')
            ->addFormItem('text','sort','排序','','0')
            ->setFormData($data)
            ->fetch();
    }


    private function store($data, $id = 0)
    {
        $this->nameExist($data['name'],$id);
        $validate = new \app\shop\validate\GoodsCategory();
        $check = $validate->check($data);
        if(!$check){
            $this->error($validate->getError());
        }
        $res = GoodsCategoryModel::store($data,$id);
        if($res){
            $this->success('保存成功','index');
        }else{
            $this->error('保存失败，请重试');
        }
    }

    private function getTopList()
    {
        $list = GoodsCategoryModel::getList(0);
        $arr = [0=>'顶级分类'];
        foreach ($list as $item){
            $arr[$item['id']] = $item['name'];
        }
        return $arr;
    }

    private function nameExist($name, $id)
    {
        $res = GoodsCategoryModel::nameExist($name,$id);
        if($res){
            $this->error('分类名称已存在');
        }
    }
}